package me.weijing.common.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;

import android.os.Environment;
import android.os.StatFs;

public class FileUtil {
    public static long getFileSize(String filePath) {
        try {
            File f = new File(filePath);
            if (f.isFile()) {
                return f.length();
            }
            return getFileSize(f);
        } catch (Exception e) {

            e.printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return 0;
    }

    public static long getFileSize(File f) throws Exception {
        long size = 0;
        File flist[] = f.listFiles();
        if (null == flist)
            return 0;
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public static FileInputStream openFile(String pathName) {
        File file = new File(pathName);
        FileInputStream fis = null;
        if (file.exists()) {
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        return fis;
    }

    public static FileOutputStream openFile4Write(String pathName) {
        File file = new File(pathName);
        FileOutputStream fos = null;

        if (file.exists()) {
            file.delete();
        }
        try {
            fos = new FileOutputStream(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fos;
    }

    public static FileOutputStream openFile4Write(String pathName, boolean bAppend) {
        File file = new File(pathName);
        FileOutputStream fos = null;

        if (file.exists() && bAppend == false) {
            file.delete();
        }
        try {
            fos = new FileOutputStream(file, bAppend);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fos;
    }

    public static long deleteFile(String filePath) {
        try {
            return removeDir(filePath);
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return 0;
    }

    public static long removeDir(String filePath) {
        File f = new File(filePath);
        return removeFile(f);
    }

    public static long removeFile(File f) {
        if (null == f)
            return 0;
        long size = 0;
        if (f.isFile()) {
            size = f.length();
            f.delete();
            return size;
        }
        File flist[] = f.listFiles();
        if (null == flist) {
            f.delete();
            return size;
        }
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size += removeFile(flist[i]);
            } else {
                size += flist[i].length();
                flist[i].delete();
            }
        }
        f.delete();
        return size;
    }

    public static boolean renameFile(String ofilePath, String nfilePath) {
        if (null == ofilePath || null == nfilePath)
            return false;
        try {
            File f = new File(ofilePath);
            File f2 = new File(nfilePath);
            f2.getParentFile().mkdirs();
            boolean bret = f.renameTo(f2);
            if (bret)
                return true;
            if (ofilePath.equals(nfilePath))
                return false;
            // fix: internal storage rename to SDCard Fail
            f2.delete();
            /* copyFile(f, f2); */
            f.delete();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return false;
    }

    public static File[] listFilesSortByModify(String dirPath) {
        File fdir = new File(dirPath);

        if (fdir.exists() == false)
            return null;
        File[] files = fdir.listFiles();
        Arrays.sort(files, new CompratorByLastModified());

        return files;
    }

    public static File[] listFilesSortBySize(String dirPath) {
        File fdir = new File(dirPath);

        if (fdir.exists() == false)
            return null;
        File[] files = fdir.listFiles();
        Arrays.sort(files, new CompratorBySize());

        return files;
    }

    public static String readFileContent(String filePath) {
        File file = new File(filePath);
        return readFileContent(file);
    }

    /**
     * 读取文件内容
     * 
     * @param file
     * @return
     */
    public static String readFileContent(File file) {
        StringBuilder text = new StringBuilder();
        FileInputStream fileIS = null;
        try {
            fileIS = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fileIS));
            String line;

            while ((line = br.readLine()) != null) {
                text.append(line);
                // text.append('\n');
            }
        } catch (Throwable e) {

            try {
                if (null != fileIS) {
                    fileIS.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return text.toString();
    }

    /**
     * 将数据写入文件中
     * 
     * @param filePath
     * @param data
     */
    public static void writeFile(String filePath, String data) {
        FileOutputStream outStream = null;
        boolean bOK = false;

        try {
            File file = new File(filePath);
            String pathDir = file.getParent();
            File dirFile = new File(pathDir);
            if (dirFile.exists() == false) {
                dirFile.mkdirs();
            }
            file.delete();
            outStream = new FileOutputStream(file);
            outStream.write(data.getBytes());
            outStream.flush();
            bOK = true;
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (null != outStream) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bOK) {
                File file = new File(filePath);
                file.renameTo(new File(filePath));
            }
        }
    }

    static class CompratorByLastModified implements Comparator<File> {
        @Override
        public int compare(File o1, File o2) {
            File file1 = o1;
            File file2 = o2;
            long diff = file1.lastModified() - file2.lastModified();
            if (diff > 0)
                return 1;
            else if (diff == 0)
                return 0;
            else
                return -1;
        }

        @Override
        public boolean equals(Object obj) {
            return true;
        }

    }

    static class CompratorBySize implements Comparator<File> {
        @Override
        public int compare(File o1, File o2) {
            File file1 = o1;
            File file2 = o2;
            long diff = file1.length() - file2.length();
            if (diff > 0)
                return 1;
            else if (diff == 0)
                return 0;
            else
                return -1;
        }

        @Override
        public boolean equals(Object obj) {
            return true;
        }
    }

    public static String getFileName(String filePathName) {
        if (filePathName != null && !"".equals(filePathName)) {
            int index = filePathName.lastIndexOf('/');
            if (index != -1 && (index + 1) < filePathName.length()) {
                return filePathName.substring(index + 1);
            }
        }
        return "";
    }

    /**
     * 
     * 
     * @return
     */
    public static boolean isExternalStorage() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 判断sd卡是否已满
     * 
     * @return
     */
    public static boolean storageIsFull() {
        StatFs fs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
        return !(fs.getAvailableBlocks() > 1);
    }

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /**
     * 是否存在sd卡
     * 
     * @return
     */
    public static boolean hasSdcard() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }
}
